#!/usr/bin/perl
#
# Copyright 2013-2014 - Xavier Berger - http://rpi-experiences.blogspot.fr/
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# web.status.1.content.1.line.4=InsertHTML("/addons/top3/top3.html")
#
my $process='rpimonitor';
my $web=1;
my $nbtop=3;
my @top=[];
my $monitored;

#Get uptime
my $uptime;
open ( FILE, "/proc/uptime") or die "Can't open /proc/uptime \n";
while (<FILE>){
  /(\S+) \S+/;
  $uptime = $_;
}

my $idx=0;
open (PS, 'ps -e -o etimes,time,comm --sort -time |') or die;
while (<PS>)
{
  /TIME/ and next;
  $idx++;
  /$process/ and $monitored->{'idx'} ||= $idx;
  /$process/ or $idx <= $nbtop or next;
  /(\S+) (\S+):(\S+):(\S+) (\S+)/;
  $1 or next;
  my $start=100*($2*60*60+$3*60+$4)/$1;
  my $total=100*($2*60*60+$3*60+$4)/$uptime;
  $web
  and $top[$idx] = sprintf("<tr><td>%3d</td><td>%02d:%02d:%02d</td><td>%-12s</td><td>( %.2f% / %.2f% )</td></tr>\n",$idx, $2, $3, $4, $5, $start, $total)
  or $top[$idx] = sprintf("%3d %02d:%02d:%02d %-12s ( %.2f% / %.2f% ) \n",$idx, $2, $3, $4, $5, $start, $total);
}
close PS or die;
my $iloop;

  $web
  and print "<table class='table'>\n"
  and print "<tr><th>#</th><th>CPU usage</th><th>Process</th><th>% start / total</th></tr>\n";
  for ($iloop=1; $iloop<=$nbtop; $iloop++)
  {
    print $top[$iloop];
  }
  if ($iloop < $monitored->{'idx'}){
    $web
    and print "<tr><td></td><td colspan='3'>...</td></tr>\n"
    or print "    ...\n";
  }
  if ($iloop <= $monitored->{'idx'}){
    print $top[$monitored->{'idx'}];
  }
  $web
  and print "</table>\n";
